<template>
  <div ref="chartRef" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
let chart = null

const initChart = () => {
  const option = {
    title: {
      text: '土壤pH值24小时变化',
      textStyle: {
        color: '#eaeaea',
        fontSize: 14
      },
      left: 20
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>{c}pH'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00'],
      axisLabel: {
        color: '#eaeaea'
      }
    },
    yAxis: {
      type: 'value',
      name: 'pH值',
      nameTextStyle: {
        color: '#eaeaea'
      },
      axisLabel: {
        color: '#eaeaea',
        formatter: '{value}'
      },
      min: 0,
      max: 14,
      splitLine: {
        lineStyle: {
          color: 'rgba(238, 238, 238, 0.1)'
        }
      }
    },
    series: [
      {
        name: '土壤pH值',
        type: 'bar',
        data: [6.8, 7.1, 6.9, 7.2, 7.0, 6.7, 6.9, 7.1],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#91cc75' },
            { offset: 0.5, color: '#67c23a' },
            { offset: 1, color: '#67c23a' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#95d475' },
              { offset: 0.7, color: '#95d475' },
              { offset: 1, color: '#b3e19d' }
            ])
          }
        }
      }
    ]
  }

  if (chart) {
    chart.setOption(option)
  } else {
    chart = echarts.init(chartRef.value)
    chart.setOption(option)
  }
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})
</script> 